package com.voxel.sense.infomsg.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.BitmapDrawable;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.example.com.common.utils.L;
import com.example.com.common.utils.SizeUtils;
import com.example.com.common.utils.ToastUtil;
import com.example.com.common.view.recycler.RecyclerAdapter;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.interfaces.listener.OnSpinnerItemClickListener;
import com.voxel.sense.infomsg.utils.GlideUtils;
import com.voxel.sense.infomsg.view.decoration.ItemDivider;
import com.voxel.sense.infomsg.view.decoration.LinearItemDecoration;

import java.util.List;

import cyy.example.com.facotry.Factory;

/**
 * Created by ChenYiYao on 2017/11/22.
 */

public class MySpinner extends LinearLayout implements RecyclerAdapter.AdapterListener<String> {
    RecyclerView mRecyclerView;
    RecyclerAdapter mAdapter;
    private TextView mSpinnerText;
    private ImageView mSpinnerImag;
    private PopupWindow popupWindow;
    private boolean isInitPopHeight = false;//标记是否初始化了popwindow的高度
    private int mPopMaxHeight = SizeUtils.dp2px(150);//允许popwindow最大的高度
    private List mList;
    private View mRoot;
    private OnSpinnerItemClickListener mItemListener;


    public MySpinner(Context context) {
        this(context, null);
    }

    public MySpinner(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mRoot = LayoutInflater.from(context).inflate(R.layout.view_spinner, this);
        mSpinnerText = mRoot.findViewById(R.id.tv_desc);
        mSpinnerText.setHint("默认选项");
        mSpinnerImag = mRoot.findViewById(R.id.iv_icon);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.my_spinner);
        if (typedArray != null) {
            String hintStr = typedArray.getString(R.styleable.my_spinner_textview_hint_text);
            mSpinnerText.setHint(hintStr);
            typedArray.recycle();
        } else {
            mSpinnerText.setHint("请选择");
        }

        initPopView(context);
        //布局完成回调，这时才能获取控件的宽度，将其赋值给popwinodw窗口
        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                getViewTreeObserver().removeOnGlobalLayoutListener(this);
                if (popupWindow != null) {
                    //设置弹出窗口的宽度
                    popupWindow.setWidth(getWidth());
                }
            }
        });
        rootOnclickEvent();
    }

    private void rootOnclickEvent() {
        L.d("rootOnclickEvent");
        mRoot.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                L.d("rootOnclickEvent-onclick");
                //显示窗口
                showWindow();
            }
        });
    }


    private void initPopView(Context context) {
        View inflate = LayoutInflater.from(context).inflate(R.layout.list_popwindow_layout, null);
        //初始化recyclerView
        mRecyclerView = inflate.findViewById(R.id.recycle_view);
        mAdapter = new RecyclerAdapter<String>(this) {

            @Override
            protected int getItemViewType(int position, String data) {
                return R.layout.item_pop_recycler_textview;
            }

            @Override
            protected ViewHolder onCreateViewHolder(View root, int viewType) {
                return new MySpinner.ViewHolder(root);
            }
        };
        mRecyclerView.addItemDecoration(new LinearItemDecoration(R.drawable.recycle_divider));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
        mRecyclerView.setAdapter(mAdapter);
        popupWindow = new PopupWindow();
        //设置一个透明背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //点击外部窗口消息
        popupWindow.setOutsideTouchable(true);
        //获取焦点
        popupWindow.setFocusable(true);
        //设置布局
        popupWindow.setContentView(inflate);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                GlideUtils.GlideLoadPic(getContext(), R.mipmap.ic_drop_unselected_icon, mSpinnerImag);
            }
        });
    }

    private void initPopWindowSize() {
        if (mList != null && mList.size() > 0) {
            int recyclerHeight = mList.size() * SizeUtils.dp2px(52);
            int height = mPopMaxHeight > recyclerHeight ? recyclerHeight : mPopMaxHeight;
            popupWindow.setHeight(height);
            isInitPopHeight = true;
        }
    }

    public void showWindow(int xoff, int yoff) {
        if (popupWindow.isShowing())
            return;
        if (!isInitPopHeight) {
            //没有初始化到窗口的大小，先初始化，不然无法弹出窗口
            initPopWindowSize();
        }
        //数据空，则不显示pop窗口
        if (mList == null || mList.size() <= 0) {
            ToastUtil.showToastLong(Factory.app(), "无法获取数据");
            return;
        }
        popupWindow.showAsDropDown(mSpinnerText, xoff, yoff);
        //显示popwndow，并改变图标drop_down_selected_icon,dropa_down_unselected_icon
        GlideUtils.GlideLoadPic(getContext(), R.mipmap.ic_drop_selected_icon, mSpinnerImag);
    }

    public void showWindow() {
        showWindow(0, 0);
    }

    public void setItemListener(OnSpinnerItemClickListener listener) {
        this.mItemListener = listener;
    }

    public String getSlectText() {
        return (String) mSpinnerText.getText();
    }

    /**
     * 下拉列表item 的点击事件
     *
     * @param holder
     * @param s
     */
    @Override
    public void onItemClick(RecyclerAdapter.ViewHolder holder, String s) {
        popupWindow.dismiss();
        mSpinnerText.setText(s);
        if (mItemListener != null) {
            mItemListener.onSpinnerItemClick(this, holder, s);
        }
    }

    /**
     * 下拉列表item 的长按事件
     *
     * @param holder
     * @param s
     */
    @Override
    public void onItemLongClick(RecyclerAdapter.ViewHolder holder, String s) {
    }

    public void setListData(List<String> data) {
        mAdapter.replace(data);
        mList = data;
        initPopWindowSize();
    }

    private static class ViewHolder extends RecyclerAdapter.ViewHolder<String> {
        TextView textView;

        public ViewHolder(View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.iv_desc_icon);
        }

        @Override
        protected void onBind(String str) {
            textView.setText(str);
        }
    }


}
